import React, { FC, useEffect, useState } from 'react'
import { Form, Input, Button, Space, Toast, CapsuleTabs } from 'antd-mobile'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'


import MyHeader from '../../components/MyHeader'
import { ShowErrorMsg, ShowMsg } from '../../utils/message'
import { reg } from '../../utils/validate'
import CaptchaBtn from '../../components/CaptchaBtn'
import { useComment, useGoBackOrMine } from '../../hooks/common'
import { UserInterFace } from '../../utils/types';
import { useLocalStorageState, useRequest } from 'ahooks'
import { findUser, captchaVerify, changepassAPI, getToken } from '../../api/api'


const PhoneCaptchaPass: FC<any> = ({
  children,
  flag
}) => {
  const {
    resetFields,
  } = useComment()

  const router = useNavigate()
  const [form] = Form.useForm()
  const [phone, setPhone] = useState<string>()
  const { GoBackOrMine } = useGoBackOrMine()
  const [query] = useSearchParams()

  const [AppPhone, setAppPhone] = useLocalStorageState<string | undefined>(
    'AppPhone',
  )
  const [AppName, setAppName] = useLocalStorageState<string | undefined>(
    'AppName',
  )
  const [AppToken, setAppToken] = useLocalStorageState<string | undefined>(
    'AppToken',
  )


  // 1.
  const checkPhone = useRequest(findUser, {
    manual: true, // 手动触发 
    onSuccess: (res: any, params) => {
      if (res.result) {
        checkCaptcha.run(form.getFieldsValue())
      } else {
        ShowErrorMsg('手机号未注册,请先去注册')
      }
    }
  })

  // 2. 
  const checkCaptcha = useRequest(captchaVerify, {
    manual: true, // 手动触发
    onSuccess: (res: any, params) => {
      if (res.data) {
        flag ? changePassAction.run({
          phone,
          password: form.getFieldValue('password')
        }) : getTokenApi.run({
          phone: phone
        })
      } else {
        ShowErrorMsg('验证码验证失败')
      }
    }
  })

  // 3. 登录
  const getTokenApi = useRequest(getToken, {
    manual: true, // 手动触发
    onSuccess: (res: any, params) => {
      if (res.code == 200) {


        ShowMsg('登录成功')
        // gotowhere("/main/mine")
        GoBackOrMine()
        setAppPhone(phone)
        setAppToken(res.token)
      }
    }
  })


  // 3. 修改密码 
  const changePassAction = useRequest(changepassAPI, {
    manual: true, // 手动触发
    onSuccess: (res: any, params) => {
      if (res.code == 200) {
        ShowMsg('密码修改成功,重新登录')
        router('/login')
      } else {
        ShowErrorMsg('密码修改失败')
      }
    }
  })


  const onFinish = (value: UserInterFace) => {
    // 三部曲 
    // 1. 先判断手机号是否注册  
    // 2. 再去验证 验证码 
    // 3. 再去获取token 

    // useRequest 
    checkPhone.run({ phone: value.phone })
  }

  useEffect(() => {
    if (query.get('phone')) {
      form.setFieldValue('phone', query.get('phone'))
    } else {
      form.setFieldValue('phone', AppPhone)
    }
    setPhone(form.getFieldValue('phone'))

  }, [])


  return (
    <div>
      <div>
        <Form layout='horizontal' mode='card' form={form} onFinish={onFinish} onFinishFailed={() => ShowErrorMsg('校验失败')}>
          <Form.Header>{flag ? '通过手机号找回密码' : '手机号+验证码登录~'}</Form.Header>
          <Form.Item
            label='手机号'
            name='phone'
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: reg.phone, message: '请输入正确的手机号' }
            ]}
          >
            <Input
              placeholder='请输入'
              clearable
              onChange={(phone: any) => setPhone(phone)}

            />
          </Form.Item>

          <CaptchaBtn phone={phone} />
          {
            children
          }
          <Form.Item >
            <div className="links">
              <Link to='/reg' style={{ color: '#ff6430' }}>注册</Link>
              {
                flag ?
                  <Link to='/login' style={{ color: '#87d068' }} >登录</Link>
                  :
                  <Link to='/findpass' style={{ color: '#87d068' }} >找回密码</Link>
              }
            </div>
          </Form.Item>

          <div  >
            <Button color="success" className='mt20' block type="submit" >验证登录</Button>
            <Button color="danger" className='mt20' block onClick={() => resetFields(form)} >重置</Button>
          </div>
        </Form>
      </div>
    </div>
  )
}

export default PhoneCaptchaPass
